#!/bin/bash
#
# setup nginx servers
#
# 08/03/2012 - created

NGINX_HOSTS="$@"
TMP_DIR=/tmp
NGINX_PORT=80


function showBar {
 percDone=$(echo 'scale=2;'$1/$2*100 | bc)
 barLen=$(echo ${percDone%'.00'})
 bar=''
 fills=''
 for (( b=0; b<$barLen; b++ ))
 do
  bar=$bar"="
 done
 blankSpaces=$(echo $((100-$barLen)))
 for (( f=0; f<$blankSpaces; f++ ))
 do
  fills=$fills"."
 done
 echo -ne '['$bar'>'$fills']: '$barLen'%\r'
}


# create VMs for hosting nginx servers
echo
gcutil addinstance --image=projects/google/images/centos-6-2-v20120621 --machine_type=n1-standard-1 --zone=us-central1-a ${NGINX_HOSTS}
echo
echo "Waiting for VMs creation to complete...."
for (( i=0; i<=9600; i++ ))
do
     showBar $i 9600
done
echo



# setup nginx instances
for ng in ${NGINX_HOSTS}
do

     # create nginx tar ball
     mkdir ${TMP_DIR}/nginx
     cp default.conf ${TMP_DIR}/nginx/default.conf.${ng}
     cp nginx.repo ${TMP_DIR}/nginx/

     NGINX_EXT_IP=`gcutil listinstances | grep ${ng} | cut -d"|" -f7 | tr -d ' '`
     NGINX_INT_IP=`gcutil listinstances | grep ${ng} | cut -d"|" -f6 | tr -d ' '`
     find ${TMP_DIR}/nginx/ -name default.conf.${ng} -type f -exec sed -i -e "s/nginx_server_internal/${NGINX_INT_IP}/g" {} \;
     find ${TMP_DIR}/nginx/ -name default.conf.${ng} -type f -exec sed -i -e "s/nginx_server/${NGINX_EXT_IP}/g" {} \;
     find ${TMP_DIR}/nginx/ -name default.conf.${ng} -type f -exec sed -i -e "s/nginx_port/${NGINX_PORT}/g" {} \;

     cd ${TMP_DIR}/nginx/
     rm -f default.conf.${ng}-e
     tar cf nginx.tar default.conf.* nginx.repo
  
     cd -
     gcutil push ${ng} getnginx.sh ${TMP_DIR}/nginx/nginx.tar ${TMP_DIR} 
     gcutil ssh ${ng} ${TMP_DIR}/getnginx.sh
done

# list URLS for nginx instances
for ng in ${NGINX_HOSTS}
do
     NGINX_URL=`gcutil listinstances | grep ${ng} | cut -d"|" -f7 | tr -d ' '`
     echo
     echo
     echo "nginx url: http://${NGINX_URL}:8080/"
done


# clean up installation files and directories
rm -rf ${TMP_DIR}/nginx

exit
